package com.example.quiz.controller;

import com.example.quiz.common.Result;
import com.example.quiz.model.User;
import com.example.quiz.model.WrongQuestion;
import com.example.quiz.service.WrongQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/wrong-question")
public class WrongQuestionController {

    @Autowired
    private WrongQuestionService wrongQuestionService;

    @GetMapping("/list")
    public String listPage() {
        return "wrong-question/list";
    }

    @GetMapping("/api/list")
    @ResponseBody
    public Result<Map<String, Object>> getList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }

        List<WrongQuestion> questions = wrongQuestionService.getPagedQuestions(page, size, user.getId());
        int total = wrongQuestionService.getTotalCount(user.getId());

        Map<String, Object> data = new HashMap<>();
        data.put("list", questions);
        data.put("total", total);

        return Result.success(data);
    }

    @DeleteMapping("/api/delete/{id}")
    @ResponseBody
    public Result<Integer> deleteWrongQuestion(
            @PathVariable Long id,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }

        int result = wrongQuestionService.deleteById(id);
        if (result > 0) {
            return Result.success(result);
        }
        return Result.error("删除失败");
    }

    @DeleteMapping("/api/clear")
    @ResponseBody
    public Result<Integer> clearWrongQuestions(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }
        int wrongQuestionCount = wrongQuestionService.getTotalCount(user.getId());
        if(wrongQuestionCount < 0){
            return Result.error("没有错题");
        }
        int result = wrongQuestionService.clearByUserId(user.getId());
        if (result > 0) {
            return Result.success(result);
        }
        return Result.error("清空失败");
    }
}
    
